package com.ruoyi.user.service.impl;

import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.ruoyi.floor.mapper.HsFloorMapper;
import com.ruoyi.household.mapper.HsHouseholdMapper;
import com.ruoyi.user.app.SecreateApp;
import com.ruoyi.user.domain.ro.LoginAppRo;
import com.ruoyi.user.domain.vo.HousehoodInfoVo;
import com.ruoyi.userMission.mapper.HsUserMissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.user.mapper.HsUserMapper;
import com.ruoyi.user.domain.HsUser;
import com.ruoyi.user.service.IHsUserService;

import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;

/**
 * 用户信息管理Service业务层处理
 *
 * @author ruoyi
 * @date 2024-07-25
 */
@Service
public class HsUserServiceImpl implements IHsUserService
{
    @Autowired
    private HsUserMapper hsUserMapper;
    @Autowired
    private HsHouseholdMapper hsHouseholdMapper;
    @Autowired
    private HsUserMissionMapper hsUserMissionMapper;
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES/GCM/NoPadding";
    private static final int AES_KEY_SIZE = 256; // AES-256
    private static final int GCM_NONCE_LENGTH = 12; // 12 bytes IV
    private static final int GCM_TAG_LENGTH = 16; // 128 bits authentication tag

    /**
     * 查询用户信息管理
     *
     * @param id 用户信息管理主键
     * @return 用户信息管理
     */
    @Override
    public HsUser selectHsUserById(Long id)
    {
        return hsUserMapper.selectHsUserById(id);
    }

    /**
     * 查询用户信息管理列表
     *
     * @param hsUser 用户信息管理
     * @return 用户信息管理
     */
    @Override
    public List<HsUser> selectHsUserList(HsUser hsUser)
    {
        return hsUserMapper.selectHsUserList(hsUser);
    }

    /**
     * 新增用户信息管理
     *
     * @param hsUser 用户信息管理
     * @return 结果
     */
    @Override
    public int insertHsUser(HsUser hsUser)
    {
        hsUser.setHouseholdId( hsUserMapper.getHouseholID(hsUser.getUserPhone()));
        return hsUserMapper.insertHsUser(hsUser);
    }

    /**
     * 修改用户信息管理
     *
     * @param hsUser 用户信息管理
     * @return 结果
     */
    @Override
    public int updateHsUser(HsUser hsUser)
    {
        return hsUserMapper.updateHsUser(hsUser);
    }

    /**
     * 批量删除用户信息管理
     *
     * @param ids 需要删除的用户信息管理主键
     * @return 结果
     */
    @Override
    public int deleteHsUserByIds(Long[] ids)
    {
        return hsUserMapper.deleteHsUserByIds(ids);
    }

    /**
     * 删除用户信息管理信息
     *
     * @param id 用户信息管理主键
     * @return 结果
     */
    @Override
    public int deleteHsUserById(Long id)
    {
        return hsUserMapper.deleteHsUserById(id);
    }

    @Override
    public int getLoginApp(LoginAppRo loginAppRo) throws Exception {
      //先通过手机号得到住户id
        SecreateApp secreateApp = new SecreateApp();
        Long househoodId = hsUserMapper.getHouseholID(loginAppRo.getUserPhone());
        //通过住户id去查到对应小区名字 楼栋名字 住户名字
        HousehoodInfoVo househoodInfo = hsHouseholdMapper.getHousehoodInfo(househoodId);
        String householdFloorName = househoodInfo.getHouseholdFloorName();
        String householdXqName = househoodInfo.getHouseholdXqName();
        String householdName = househoodInfo.getHouseholdName();
        //住户id加密
        String househoodIdSecreate = extracted(String.valueOf(househoodId).toString());

        //由小区楼栋住户名字 得到任务id
        Long taskId = hsUserMissionMapper.getMission(householdFloorName, householdXqName, householdName);
        //住户任务id加密
        String taskIdSecreate = extracted(String.valueOf(taskId));
        String text =  "http://localhost/hslog?"+househoodIdSecreate+"&"+"task=FJE33JF";

        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, 200, 200);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timestamp = dateFormat.format(new Date());
        Path path = FileSystems.getDefault().getPath("D:\\erweima"+"\\"+timestamp);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);

        return 0;
    }

    private String extracted(String sensitiveData) throws Exception {
        // 生成AES密钥
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(AES_KEY_SIZE);
        SecretKey secretKey = keyGenerator.generateKey();

        // 生成GCM的IV
        byte[] iv = new byte[GCM_NONCE_LENGTH];
        SecureRandom random = new SecureRandom();
        random.nextBytes(iv);

        // 加密
        /*  String sensitiveData = "123";*/
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
        byte[] encryptedBytes = cipher.doFinal(sensitiveData.getBytes());
        String encryptedData = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted data: " + encryptedData);
        return encryptedData;

    /*    // 解密
        cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        String decryptedData = new String(decryptedBytes);
        System.out.println("Decrypted data: " + decryptedData);*/

    }


}
